package com.example.consumer.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Auther: GongXl
 * @Date: 2021/3/31 13:43
 * @Description:
 */
@RestController
@Slf4j
public class ConsumerController {
    @Autowired
    private DiscoveryClient discoveryClient;
//    不能自动装载
    @Autowired
    private RestTemplate restTemplate;
    @RequestMapping("/instances")
    public List<ServiceInstance> instances(){
        List<ServiceInstance> provider = this.discoveryClient.getInstances("provider");
        return provider;

    }
    @RequestMapping("/index")
    public String index(){
        List<ServiceInstance> list = this.discoveryClient.getInstances("provider");
        int index = ThreadLocalRandom.current().nextInt(list.size());
        ServiceInstance serviceInstance = list.get(index);
        String url = serviceInstance.getUri() + "/index";
        log.info("调用的端口是：",serviceInstance.getPort());
        return "调用了端口："+serviceInstance.getPort()+"的服务，返回结果："+this.restTemplate.getForObject(url,String.class);
    }
}